'''
任务依赖和文件相关的API路由
'''
from flask import Blueprint, request, jsonify, g, current_app
from psycopg2.extras import RealDictCursor
from utils.helpers import check_task_dependencies, update_task_progress, add_task_dependency

# 创建蓝图
dependency_bp = Blueprint('dependency', __name__, url_prefix='/api')

# 12. 获取文件变更历史
@dependency_bp.route('/files/history', methods=['GET'])
def get_file_history():
    file_path = request.args.get('path')
    
    if not file_path:
        return jsonify({
            'status': 'error',
            'message': '文件路径不能为空'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT 
        fc.*, 
        te.started_at, te.completed_at, te.executor,
        st.title as task_title
    FROM file_changes fc
    JOIN task_executions te ON fc.execution_id = te.id
    JOIN sub_tasks st ON te.sub_task_id = st.id
    WHERE fc.file_path = %s
    ORDER BY fc.created_at DESC
    ''', (file_path,))
    
    changes = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': {
            'file_path': file_path,
            'changes': changes
        }
    })

# 13. 添加任务依赖关系
@dependency_bp.route('/tasks/<int:dependent_task_id>/dependencies', methods=['POST'])
def add_dependency(dependent_task_id):
    data = request.get_json()
    
    if not data or 'dependency_task_id' not in data:
        return jsonify({
            'status': 'error',
            'message': '依赖任务ID不能为空'
        }), 400
    
    dependency_task_id = data['dependency_task_id']
    dependency_type = data.get('dependency_type', 'finish_to_start')
    is_critical = data.get('is_critical', False)
    
    # 检查任务是否存在
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('SELECT * FROM sub_tasks WHERE id = %s', (dependent_task_id,))
    dependent_task = cursor.fetchone()
    
    if not dependent_task:
        return jsonify({
            'status': 'error',
            'message': '依赖方任务不存在'
        }), 404
    
    cursor.execute('SELECT * FROM sub_tasks WHERE id = %s', (dependency_task_id,))
    dependency_task = cursor.fetchone()
    
    if not dependency_task:
        return jsonify({
            'status': 'error',
            'message': '被依赖任务不存在'
        }), 404
    
    # 添加依赖关系
    dependency = add_task_dependency(dependent_task_id, dependency_task_id, dependency_type, is_critical)
    
    if dependency:
        # 如果任务处于待执行状态且依赖任务未完成，则标记为阻塞状态
        if dependent_task['status'] == 'pending' and dependency_task['status'] != 'completed':
            update_task_progress(
                dependent_task_id, 
                dependent_task['progress'], 
                'blocked', 
                f'被任务#{dependency_task_id}（{dependency_task["title"]}）阻塞'
            )
        
        return jsonify({
            'status': 'success',
            'message': '任务依赖关系添加成功',
            'data': dependency
        })
    else:
        return jsonify({
            'status': 'error',
            'message': '添加任务依赖关系失败，可能是依赖关系已存在'
        }), 400

# 14. 获取任务的依赖关系
@dependency_bp.route('/tasks/<int:task_id>/dependencies', methods=['GET'])
def get_dependencies(task_id):
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取任务依赖的任务
    cursor.execute('''
    SELECT 
        td.*, 
        st.title as dependency_title,
        st.status as dependency_status,
        st.progress as dependency_progress
    FROM task_dependencies td
    JOIN sub_tasks st ON td.dependency_task_id = st.id
    WHERE td.dependent_task_id = %s
    ''', (task_id,))
    
    dependencies = cursor.fetchall()
    
    # 获取依赖于当前任务的任务
    cursor.execute('''
    SELECT 
        td.*, 
        st.title as dependent_title,
        st.status as dependent_status,
        st.progress as dependent_progress
    FROM task_dependencies td
    JOIN sub_tasks st ON td.dependent_task_id = st.id
    WHERE td.dependency_task_id = %s
    ''', (task_id,))
    
    dependents = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': {
            'dependencies': dependencies,
            'dependents': dependents
        }
    })

# 15. 移除任务依赖关系
@dependency_bp.route('/tasks/dependencies/<int:dependency_id>', methods=['DELETE'])
def remove_dependency(dependency_id):
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取依赖关系信息
    cursor.execute('SELECT * FROM task_dependencies WHERE id = %s', (dependency_id,))
    dependency = cursor.fetchone()
    
    if not dependency:
        return jsonify({
            'status': 'error',
            'message': '依赖关系不存在'
        }), 404
    
    # 删除依赖关系
    cursor.execute('DELETE FROM task_dependencies WHERE id = %s', (dependency_id,))
    
    # 检查任务是否还有其他依赖
    cursor.execute('''
    SELECT COUNT(*) as dependency_count 
    FROM task_dependencies 
    WHERE dependent_task_id = %s
    ''', (dependency['dependent_task_id'],))
    
    dependency_count = cursor.fetchone()['dependency_count']
    
    # 如果没有其他依赖且任务状态为 blocked，则更新为pending
    if dependency_count == 0:
        cursor.execute('''
        SELECT * FROM sub_tasks 
        WHERE id = %s AND status = 'blocked'
        ''', (dependency['dependent_task_id'],))
        
        blocked_task = cursor.fetchone()
        if blocked_task:
            update_task_progress(
                blocked_task['id'], 
                blocked_task['progress'], 
                'pending', 
                '依赖关系已移除，任务可以执行'
            )
    
    conn.commit()
    
    return jsonify({
        'status': 'success',
        'message': '任务依赖关系已移除'
    }) 
